using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model;
using WPF_MVVM_Test.MVVM_Model.Plan;
using WPF_MVVM_Test.Services.Plan;

namespace WPF_MVVM_Test.MVVM_ViewModel.Plan
{
    public class SelectProductViewModel : BaseViewModel
    {
        private readonly ProductService _productService;
        private readonly int _pageSize = 10;
        
        private ObservableCollection<ProductModel> _products = new();
        private ProductModel? _selectedProduct;
        private string _searchMaterialNumber = string.Empty;
        private bool _isLoading = false;
        private int _currentPage = 1;
        private int _totalCount = 0;
        private int _totalPage = 0;

        public ObservableCollection<ProductModel> Products
        {
            get => _products;
            set => SetProperty(ref _products, value);
        }

        public ProductModel? SelectedProduct
        {
            get => _selectedProduct;
            set => SetProperty(ref _selectedProduct, value);
        }

        public string SearchMaterialNumber
        {
            get => _searchMaterialNumber;
            set => SetProperty(ref _searchMaterialNumber, value);
        }

        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        public int TotalPage
        {
            get => _totalPage;
            set => SetProperty(ref _totalPage, value);
        }

        public string PageInfo => $"第 {CurrentPage} 页，共 {TotalPage} 页，总计 {TotalCount} 条记录";

        public bool CanGoPreviousPage => CurrentPage > 1;
        public bool CanGoNextPage => CurrentPage < TotalPage;

        public ICommand SearchCommand { get; }
        public ICommand ResetCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        public ICommand ConfirmCommand { get; }

        public SelectProductViewModel()
        {
            _productService = new ProductService();
            
            SearchCommand = CreateCommand(async () => await SearchProductsAsync());
            ResetCommand = CreateCommand(Reset);
            PreviousPageCommand = CreateCommand(async () => await PreviousPageAsync());
            NextPageCommand = CreateCommand(async () => await NextPageAsync());
            ConfirmCommand = CreateCommand(Confirm);

            // 初始加载数据
            _ = LoadDataAsync();
        }

        private async Task LoadDataAsync()
        {
            try
            {
                IsLoading = true;
                var (products, totalCount, totalPage) = await _productService.GetProductsAsync(
                    SearchMaterialNumber, "", "", "", CurrentPage, _pageSize);
                
                Products = new ObservableCollection<ProductModel>(products);
                TotalCount = totalCount;
                TotalPage = totalPage;
                
                OnPropertyChanged(nameof(PageInfo));
                OnPropertyChanged(nameof(CanGoPreviousPage));
                OnPropertyChanged(nameof(CanGoNextPage));
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"加载产品数据失败：{ex.Message}", "错误",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async Task SearchProductsAsync()
        {
            try
            {
                IsLoading = true;
                CurrentPage = 1;
                var (products, totalCount, totalPage) = await _productService.GetProductsAsync(
                    SearchMaterialNumber, "", "", "", CurrentPage, _pageSize);
                
                Products = new ObservableCollection<ProductModel>(products);
                TotalCount = totalCount;
                TotalPage = totalPage;
                
                OnPropertyChanged(nameof(PageInfo));
                OnPropertyChanged(nameof(CanGoPreviousPage));
                OnPropertyChanged(nameof(CanGoNextPage));
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"搜索产品失败：{ex.Message}", "错误",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private void Reset()
        {
            SearchMaterialNumber = string.Empty;
            _ = LoadDataAsync();
        }

        private async Task PreviousPageAsync()
        {
            if (CanGoPreviousPage)
            {
                CurrentPage--;
                await LoadDataAsync();
            }
        }

        private async Task NextPageAsync()
        {
            if (CanGoNextPage)
            {
                CurrentPage++;
                await LoadDataAsync();
            }
        }

        private void Confirm()
        {
            if (SelectedProduct == null)
            {
                System.Windows.MessageBox.Show("请选择一个产品！", "提示",
                    System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return;
            }

            // 关闭对话框并返回结果
            if (System.Windows.Application.Current.Windows.Count > 0)
            {
                foreach (System.Windows.Window window in System.Windows.Application.Current.Windows)
                {
                    if (window is WPF_MVVM_Test.MVVM_View.Dialog.SelectProductDialog dialog)
                    {
                        dialog.DialogResult = true;
                        dialog.Close();
                        break;
                    }
                }
            }
        }
    }
}

